package com.mine.async.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mine.async.domain.pojo.DownloadJobBO;
import com.mine.async.enums.JobStatusEnum;
import com.mine.async.jobexe.DownloadJobExecutor;
import com.mine.async.mapper.DownloadJobMapper;
import com.mine.async.service.IDownloadJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DownloadJobServiceImpl extends SuperServiceImpl<DownloadJobMapper, DownloadJobBO> implements IDownloadJobService {

    @Override
    public void updateJobRatio(String jobNo, Integer ratio) {
        if (StrUtil.isEmpty(jobNo) || ObjectUtil.isNull(ratio))
            return;
        DownloadJobBO job = getByJobNo(jobNo);
        if (ObjectUtil.isNotNull(job)) {
            DownloadJobBO jobUp = new DownloadJobBO();
            jobUp.setId(job.getId());
            jobUp.setJobRatio(ratio);
            super.updateById(jobUp);
        }
    }

    @Override
    public DownloadJobBO getByJobNo(String jobNo) {
        if (StrUtil.isEmpty(jobNo))
            return null;
        return this.lambdaQuery()
                .eq(DownloadJobBO::getJobNo, jobNo)
                .last(LIMIT_ONE)
                .one();
    }

    @Override
    public List<DownloadJobBO> queryRetryJob() {
        List<DownloadJobBO> list = this.lambdaQuery()
                .in(DownloadJobBO::getJobStatus, Arrays.asList(JobStatusEnum.RUNING.getCode(), JobStatusEnum.READY, JobStatusEnum.EXCEPTION.getCode()))
                .list();
        list = list.stream()
                .filter(j1 -> !ObjectUtil.equals(DownloadJobExecutor.RUNING_MAP.get(j1.getJobNo()), JobStatusEnum.RUNING.getCode()))
                .filter(j2 -> {
                    if (j2.getRetryCount() == null || j2.getRetryCount() == 0) {
                        return false;
                    }
                    if (j2.getFailRetryNum() == null) {
                        return true;
                    }
                    return j2.getRetryCount() > j2.getFailRetryNum();
                })
                .collect(Collectors.toList());
        return list;
    }
}
